package com.runningboy.cluster.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Description: 创建消费者（创建消费者的过程与创建生产者的过程类似）
 * @Author Runningboy
 * @Date 2020/7/25 17:13
 * @Version 1.0
 */
public class ConsumerCluster {
    //failvoer：activemq的失效转移机制
    private static final String mqUrl = "failover:(tcp:// 192.168.0.101:61617,tcp:// 192.168.0.101:61618)";//activeMq默认的tcp端口是61616
    private static final String topicName = "topic-test";

    public static void main(String[] args) throws JMSException {
        //1、创建ConnectionFactory
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        //2、创建Connetion
        Connection connection = connectionFactory.createConnection();
        //3、启动连接
        connection.start();
        //4、创建会话
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);//session自动应答

        //5、创建一个目标
        Destination destination = session.createTopic(topicName);

        //6、创建一个消费者
        MessageConsumer consumer = session.createConsumer(destination);

        //7、创建一个监听器(消息的监听是异步执行的)
        consumer.setMessageListener(
                new MessageListener() {
                    public void onMessage(Message message) {
                        TextMessage textMessage = (TextMessage) message;
                        try {
                            System.out.println("接收消息"+textMessage.getText());
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                }
        );
    }
}
